package com.youjiang.meeting.utils.weixin;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.thoughtworks.xstream.XStream;
import com.youjiang.meeting.utils.weixinbean.Articles;
import com.youjiang.meeting.utils.weixinbean.NewsMessage;
import com.youjiang.meeting.utils.weixinbean.TextMessage;


public class MessageUtil {
	public static final String MESSAGE_TEXT = "text";
	public static final String MESSAGE_IMAGE = "image";// 图片
	public static final String MESSAGE_VOICE = "voice";// 语音
	public static final String MESSAGE_VIDEO = "video";// 视频
	public static final String MESSAGE_SHORTVIDEO = "shortvideo";// 小视频
	public static final String MESSAGE_LOCATION = "location";// 地理
	public static final String MESSAGE_LINK = "link";// 连接
	public static final String MESSAGE_EVENT = "event";// 事件
	public static final String MESSAGE_SUBSCRIBE = "subscribe";// 关注
	public static final String MESSAGE_NEWS = "news";// 关注
	public static final String MESSAGE_CLICK = "CLICK";
	public static final String MESSAGE_LOCATION_SELECT = "location_select";
	public static final String MESSAGE_LOCATION_L = "LOCATION";

	public static Map<String, String> XMLToMessage(HttpServletRequest req)
			throws IOException, DocumentException {
		Map<String, String> map = new HashMap<String, String>();
		SAXReader sax = new SAXReader();
		InputStream in = req.getInputStream();
		Document docu = sax.read(in);
		Element element = docu.getRootElement();
		List<Element> list = element.elements();
		for (Element e : list) {
			if (e.elements().size() > 0) {
				List<Element> li = e.elements();
				for (Element it : li) {
					map.put(it.getName(), it.getText());
				}
			} else {
				map.put(e.getName(), e.getText());
			}
		}
		return map;
	}

	// 把TextMessage的转成xml的字符串
	public static String textMessageToXML(TextMessage message) {
		XStream stream = new XStream();
		stream.alias("xml", message.getClass());
		return stream.toXML(message);
	}

	// 把NewsMessage转成xml的字符串
	public static String newsMessageToXML(NewsMessage message) {
		XStream stream = new XStream();
		stream.alias("xml", message.getClass());
		stream.alias("item", Articles.class);
		return stream.toXML(message);
	}
}
